package com.njupt.HashTable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 350. 两个数组的交集 II
 */
public class Intersect {
    public int[] intersect(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;

        HashMap<Integer, Integer> map = new HashMap<>();
        ArrayList<Integer> integers = new ArrayList<>();
        if(len1<len2){
            int value;
            for (int i = 0; i < len1; i++) {
                value = map.getOrDefault(nums1[i], 0) + 1;
                map.put(nums1[i],value);
            }
            Integer i1;
            for (int i = 0; i < len2; i++) {
                if(map.containsKey(nums2[i])){
                    i1 = map.get(nums2[i]);
                    map.put(nums2[i],--i1);
                    if(i1>=0){
                        integers.add(nums2[i]);
                    }
                }
            }
        }else {
            int value;
            for (int i = 0; i < len2; i++) {
                value = map.getOrDefault(nums2[i], 0) + 1;
                map.put(nums2[i],value);
            }
            Integer i1;
            for (int i = 0; i < len1; i++) {
                if(map.containsKey(nums1[i])){
                   i1 =  map.get(nums1[i]);
                   map.put(nums1[i],--i1);
                   if(i1>=0){
                       integers.add(nums1[i]);
                   }

                }
            }
        }

        int[] result = new int[integers.size()];
        for (int i = 0; i < integers.size(); i++) {
            result[i] = integers.get(i);
        }
        return result;
    }



    public static void main(String[] args) {
        Intersect test = new Intersect();

        int[] nums1 = {4,9,5};
        int[] nums2 = {9,4,9,8,4};
        int[] result = test.intersect(nums1, nums2);
        System.out.println(Arrays.toString(result));
    }
}
